package Routers

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"server5/Dao"
	"server5/Interface"
	"server5/protobuf"
	"server5/server"
	"server5/utils"
)

type Login struct {

}

func (l Login) Func(request Interface.IRequest) {

	if request.GetConnection().User().Status() != utils.NotLogin {
		fmt.Println("不处理登陆消息")
		return
	}

	fmt.Println("开始处理登陆消息")

 	var (
		loginMsg protobuf.LoginMsg
		loginResultMsg protobuf.LoginResultMsg
 	)

	//反序列化
	proto.Unmarshal(request.GetData(),&loginMsg)

 	user, _ := Dao.GetUserDao().FindUserInfo(loginMsg.UserName)
 	if user.UserPwd != loginMsg.UserPwd{
 		loginResultMsg.Flag = false
 		loginResultMsg.Result = "用户名或密码错误"

		//Debug
		fmt.Println("用户名或密码错误")

	} else {
		//判断用户是否已在线
		if server.GetGameLobby().AddOnlineUser(user.UserName,request.GetConnection().User()) {

			request.GetConnection().User().SetUserInfo(user)
			request.GetConnection().User().SetStatus(utils.Online)

			loginResultMsg.Flag = true
			loginResultMsg.Result = "登陆成功"
			loginResultMsg.OnlineUsers = server.GetGameLobby().GetAllOnlineUserName()
			//Debug
			fmt.Println("登陆成功")

			//更新用户信息
			server.GetGameLobby().UpdateOnlineUsers()

			userDao := Dao.GetUserDao()
			userInfo,_ := userDao.FindUserInfo(loginMsg.UserName)

			userInfoMsg := protobuf.UserInfoMsg{
				UserName:       userInfo.UserName,
				UserLv:         int32(userInfo.UserLv),
				UserExp:        int32(userInfo.UserExp),
				ExpLimit:       int32(utils.ExpList[userInfo.UserLv]),
				UserSp:         int32(userInfo.UserSp),
				UserGold:       int32(userInfo.UserGold),
				ReplayHp_Level: int32(userInfo.ReplyHpLevel),
				Damage_Level:    int32(userInfo.DamageLevel),
				CallBoss_Level: int32(userInfo.CallBossLevel),
				Infantry_Level: int32(userInfo.InfantryLevel),
				Archer_Level:   int32(userInfo.ArcherLevel),
			}
			request.GetConnection().SendMsg(protobuf.MsgType_UserInfo,&userInfoMsg)
			fmt.Println("用户信息发送成功")
		} else {
			loginResultMsg.Flag = false
			loginResultMsg.Result = "该用户已在线"

			//Debug
			fmt.Println("该用户已在线")
		}
	}

	request.GetConnection().SendMsg(protobuf.MsgType_LoginResult,&loginResultMsg)
	return
}